package com.zhihuishu.micro.course.openapi.app.impl.teacher;

import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import redis.clients.jedis.Jedis;

import com.zhihuishu.micro.course.log.LoggerCollectionEnum;
import com.zhihuishu.micro.course.log.LoggerTemplateUtil;
import com.zhihuishu.micro.course.model.KnowledgePoint;
import com.zhihuishu.micro.course.openapi.app.dto.KnowledgePointOpenDto;
import com.zhihuishu.micro.course.openapi.app.teacher.KnowLedgeOpenService;
import com.zhihuishu.micro.course.service.KnowLedgePointService;
import com.zhihuishu.micro.course.service.LessonService;
import com.zhihuishu.micro.course.service.LessonVideoService;
import com.zhihuishu.remote.RemoteResult;
import com.zhihuishu.toolkit.helper.BeanHelper;
import com.zhihuishu.toolkit.jedis.JedisHelper.Handler;
import com.zhihuishu.toolkit.jedis.template.JedisExecutor;

/**
 * 知识点接口的实现类
 * 
 * @author 嵇鹏
 * @descption:
 * 
 * 
 */
@Service(value="knowLedgeOpenServiceForTeacherApp")
public class KnowLedgeOpenServiceImpl implements KnowLedgeOpenService {

    protected Logger logger = LoggerFactory.getLogger(getClass());

    @Resource
    private JedisExecutor jedisExecutor;

    @Resource
    private KnowLedgePointService knowLedgePointService;// 知识点

    @Resource
    private LessonService lessonService;

    @Resource
    private LessonVideoService lessonVideoService;

    @Override
    public RemoteResult<List<Integer>> saveKnowLedgePoints(
            List<KnowledgePointOpenDto> knowledgePointOpenDtos, final Integer lessonId,
            final Integer LessonVideoId, Long courseId, Long userId) {
        RemoteResult<List<Integer>> remoteResult = new RemoteResult<List<Integer>>();
        try {
            Assert.notNull(knowledgePointOpenDtos, "知识点列表对象不能为空");
            if (logger.isDebugEnabled()) {
                logger.debug("要保存的对象列表为:{}", knowledgePointOpenDtos);
            }
            List<KnowledgePoint> knowledgePoints = BeanHelper.transTo(knowledgePointOpenDtos,
                    KnowledgePoint.class);
            List<Integer> list = knowLedgePointService.saveKnowledgePoints(knowledgePoints, lessonId,
                    LessonVideoId);
            jedisExecutor.execute( new Handler() {
                @Override
                public void handle(Jedis jedis) {
                    if (LessonVideoId != null) {// 小节
                        Long count = jedis.scard("LESSON_VIDEO_KNOWLEDEG" + LessonVideoId);
                        if (count > 0) {// 大于0表示存在知识点
                            lessonVideoService.updateLeessonVideoKnowledgeFlag(LessonVideoId, 1);// 更新小节中是否存在知识点的状态
                            lessonVideoService.touchLessonVideo(LessonVideoId);// 更新缓存
                        }
                    } else {// 节
                        Long count = jedis.scard("LESSON_KNOWLEDGE" + lessonId);
                        if (count > 0) {
                            lessonService.updatLessonKnowLedgeFlag(lessonId, 1);// 更新数据库
                            lessonService.touchLesson(lessonId);// 更新缓存

                        }
                    }
                }
            });
            LoggerTemplateUtil.saveLogger(String.format("保存知识点%s", list), userId,
                    LoggerCollectionEnum.knowLedgePoint, courseId);// 日志
            remoteResult.setResult(list);
        } catch (Exception e) {
            remoteResult.setExceptionStack(e);
            remoteResult.setSuccess(false);
        }
        return remoteResult;
    }

    @Override
    public RemoteResult<List<KnowledgePointOpenDto>> queryKnowLedgePointByLIdOrLVId(Integer lessonId,
            Integer lessonVideoId) {
        RemoteResult<List<KnowledgePointOpenDto>> remoteResult = new RemoteResult<List<KnowledgePointOpenDto>>();
        try {
            if (lessonId == null && lessonVideoId == null) {
                Assert.notNull(null, "传递参数不能全部为null");
            }
            List<KnowledgePoint> knowledgePoints = knowLedgePointService.queryKnowLedgesByLidOrLVid(lessonId,
                    lessonVideoId);
            List<KnowledgePointOpenDto> knowledgePointOpenDtos = BeanHelper.transTo(knowledgePoints,
                    KnowledgePointOpenDto.class);
            remoteResult.setResult(knowledgePointOpenDtos);
        } catch (Exception e) {
            remoteResult.setExceptionStack(e);
            remoteResult.setSuccess(false);
        }
        return remoteResult;

    }

    @Override
    public RemoteResult<Void> updateKnowledgePoint(KnowledgePointOpenDto knowledgePointOpenDto,
            Long courseId, Long userId) {
        RemoteResult<Void> remoteResult = new RemoteResult<Void>();
        try {
            Assert.notNull(knowledgePointOpenDto, "更新对象不能为空");
            Assert.notNull(knowledgePointOpenDto.getId(), "主键不能为空");
            Assert.notNull(knowledgePointOpenDto.getKnowledgePoint(), "更新内容不能为空");
            if (logger.isDebugEnabled()) {
                logger.debug("要更新的对象:{}", knowledgePointOpenDto);
            }
            knowLedgePointService.updateKnowledgePoint(BeanHelper.transTo(knowledgePointOpenDto,
                    KnowledgePoint.class));
            LoggerTemplateUtil.saveLogger(
                    String.format("更新知识点%d内容为%s", knowledgePointOpenDto.getId(),
                            knowledgePointOpenDto.getKnowledgePoint()), userId,
                    LoggerCollectionEnum.knowLedgePoint, courseId);
        } catch (Exception e) {
            remoteResult.setExceptionStack(e);
            remoteResult.setSuccess(false);
        }
        return remoteResult;
    }

    @Override
    public RemoteResult<Void> deleteKnowLedgePoint(List<Integer> ids, final Integer lessonId,
            final Integer lessonVideoId, Long courseId, Long userId) {
        RemoteResult<Void> remoteResult = new RemoteResult<Void>();
        try {
            Assert.notNull(ids, "要删除id不能为空");
            Assert.isTrue(ids.size() > 0, "列表不能为空");
            for (Integer integer : ids) {
                Assert.notNull(integer, "列表中不能包含空元素");
            }
            if (logger.isDebugEnabled()) {
                logger.debug("要删除的知识点列表{}", ids);
            }
            knowLedgePointService.deleteKnowLedgePoint(ids, lessonId, lessonVideoId, courseId);
            jedisExecutor.execute( new Handler() {

                @Override
                public void handle(Jedis jedis) {
                    if (lessonVideoId != null) {// 小节
                        Long count = jedis.scard("LESSON_VIDEO_KNOWLEDEG" + lessonVideoId);
                        if (logger.isDebugEnabled()) {
                            logger.debug("小节{}还有的知识点数量为{}",lessonVideoId,count);
                        }
                        if (count == 0) {// 大于0表示存在知识点
                            lessonVideoService.updateLeessonVideoKnowledgeFlag(lessonVideoId, 0);// 更新小节中是否存在知识点的状态
                            lessonVideoService.touchLessonVideo(lessonVideoId);// 更新缓存
                        }
                    } else {
                        Long count = jedis.scard("LESSON_KNOWLEDGE" + lessonId);
                        if (logger.isDebugEnabled()) {
                            logger.debug("节{}还有的知识点数量为{}",lessonId,count);
                        }
                        if (0 == count) {
                            lessonService.updatLessonKnowLedgeFlag(lessonId, 0);// 更新数据库
                            lessonService.touchLesson(lessonId);// 更新缓存
                        }
                    }

                }
            });

            LoggerTemplateUtil.saveLogger(String.format("删除知识点列表ids:%s", ids), userId,
                    LoggerCollectionEnum.knowLedgePoint, courseId);
        } catch (Exception e) {
            remoteResult.setExceptionStack(e);
            remoteResult.setSuccess(false);
        }
        return remoteResult;
    }

}
